<template>
  <div class="product-details" v-if="info.id">
    <div class="product-container">
      <!-- 商品基本信息区域 -->
      <div class="product-main">
        <el-row :gutter="20">
          <!-- 左侧商品图片轮播 -->
          <el-col :span="10">
            <div class="product-gallery">
              <el-carousel indicator-position="outside" height="400px" ref="carousel" :initial-index="currentImage">
                <el-carousel-item v-for="item in info.imgList.split('，')" :key="item">
                  <el-image :src="item" fit="contain" class="gallery-image"/>
                </el-carousel-item>
              </el-carousel>
              <div class="thumbnail-list">
                <div v-for="(item, index) in info.imgList.split('，')" :key="index"
                     class="thumbnail-item" @click="setCurrentImage(index)"
                     :class="{ active: currentImage === index }">
                  <el-image :src="item" fit="cover"/>
                </div>
              </div>
            </div>
          </el-col>

          <!-- 右侧商品信息 -->
          <el-col :span="14">
            <div class="product-info">
              <h1 class="product-title">{{ info.name }}</h1>
              
              <!-- 价格区域 -->
              <div class="price-section">
                <div class="price-label">价格</div>
                <div class="price-value">¥{{ info.price }}</div>
                <div class="original-price" v-if="info.originalPrice">原价: ¥{{ info.originalPrice }}</div>
              </div>

              <!-- 促销信息 -->
              <div class="promotion-section">
                <div class="promotion-item">
                  <el-tag type="danger" effect="dark">限时优惠</el-tag>
                  <span>满300减30</span>
                </div>
                <div class="promotion-item">
                  <el-tag type="warning">优惠券</el-tag>
                  <span>领券满199减20</span>
                </div>
              </div>

              <!-- 服务承诺 -->
              <div class="service-section">
                <div class="service-item">
                  <el-icon><CircleCheck /></el-icon>
                  <span>正品保证</span>
                </div>
                <div class="service-item">
                  <el-icon><CircleCheck /></el-icon>
                  <span>极速发货</span>
                </div>
                <div class="service-item">
                  <el-icon><CircleCheck /></el-icon>
                  <span>7天无理由退换</span>
                </div>
              </div>

              <!-- 选择区域 -->
              <div class="selection-section">
                <div class="selection-item">
                  <span class="label">数量</span>
                  <el-input-number v-model="quantity" :min="1" :max="info.stock" size="small"/>
                  <span class="stock">库存: {{ info.stock }}件</span>
                </div>
              </div>

              <!-- 操作按钮 -->
              <div class="action-section">
                <el-button type="danger" size="large" @click="buy" class="blf">立即购买</el-button>
                <el-button type="warning" size="large" @click="addShoppingCart" class="brt">加入购物车</el-button>
                <div class="collect-btn" @click="info.collect ? removeCollect() : addCollect()">
                  <el-icon :class="info.collect ? 'collected' : ''">
                    <Star v-if="!info.collect"/>
                    <StarFilled v-else/>
                  </el-icon>
                  <span>{{ info.collect ? '已收藏' : '收藏' }}</span>
                </div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>

      <!-- 商品详情区域 -->
      <div class="product-detail-section">
        <el-tabs v-model="activeName" class="detail-tabs">
          <el-tab-pane label="商品详情" name="detail">
            <div class="detail-content" v-html="info.intro"></div>
          </el-tab-pane>
          <el-tab-pane label="规格参数" name="specs">
            <div class="specs-content">
              <el-descriptions :column="2" border>
                <el-descriptions-item label="商品名称">{{ info.name }}</el-descriptions-item>
                <el-descriptions-item label="商品编号">{{ info.id }}</el-descriptions-item>
                <el-descriptions-item label="商品分类">{{ info.productTypeName }}</el-descriptions-item>
                <el-descriptions-item label="商品品牌">{{ info.brand || '暂无' }}</el-descriptions-item>
              </el-descriptions>
            </div>
          </el-tab-pane>
          <el-tab-pane label="商品评价" name="reviews">
            <ProductOrderEvaluate :productId="info.id"/>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>

    <!-- 购买对话框 -->
    <el-dialog
        v-model="buyDialogOpen"
        title="确认订单"
        width="500px"
        destroy-on-close
    >
      <el-form ref="buyFormRef" :model="productOrder" label-width="100px">
        <el-form-item label="收货地址" prop="shippingAddressId"
                      :rules="[{required:true,message:'请选择收货地址',trigger:['blur','change']}]">
          <el-select v-model="productOrder.shippingAddressId" placeholder="请选择" filterable>
            <el-option 
              v-for="item in shippingAddressList" 
              :key="item.id"
              :label="item.name + '_' + item.tel + '_' + item.address" 
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="购买数量" prop="quantity"
                      :rules="[{required:true,message:'请输入购买数量',trigger:['blur','change']}]">
          <el-input-number v-model="productOrder.quantity" :min="1" :max="info.stock"/>
        </el-form-item>
        <el-form-item label="订单备注" prop="remark">
          <el-input type="textarea" :rows="3" v-model="productOrder.remark" placeholder="请输入订单备注（选填）"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="buyDialogOpen = false">取消</el-button>
          <el-button type="primary" @click="buySubmit">提交订单</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import request from "@/utils/http.js";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { CircleCheck, Star, StarFilled } from '@element-plus/icons-vue';
import ProductOrderEvaluate from "@/components/ProductOrderEvaluate.vue";
import tools from "@/utils/tools.js";

const route = useRoute();
const router = useRouter();
const id = ref(route.params.id);
const info = ref({});
const quantity = ref(1);
const activeName = ref('detail');
const currentImage = ref(0);
const carousel = ref(null);

getInfo()

function getInfo() {
  request.get("/api/product/" + id.value).then(res => {
    if (res.code === 1) {
      info.value = res.data;
      console.log(info.value)
    } else {
      ElMessage.error("获取商品信息失败");
    }
  }).catch(error => {
    ElMessage.error("获取商品信息失败: " + error.message);
  });
}

const shippingAddressList = ref([])
getShippingAddressList();

async function getShippingAddressList() {
  const userInfo = tools.parseToken();
  let data = {
    pageNum: 1,
    pageSize: 100,
    uid: userInfo.id,
    qwe:1
  }
  request.get("/api/shippingAddress/page", {
    params: data
  }).then(res => {
    shippingAddressList.value = res.data.list;
  });
}

function addCollect() {
  if (!tools.getToken()) {
    ElMessage({
      message: "请先登录后再收藏",
      type: 'warning'
    });
    router.push('/login');
    return;
  }
  
  request.post("/api/productCollect/add", id.value).then(res => {
    if (res.code === 1) {
      console.log(res.data)
      info.value.collect = res.data;
      ElMessage({
        message: "收藏成功",
        type: 'success'
      });
    } else {
      ElMessage.error(res.msg || "收藏失败");
    }
  }).catch(error => {
    ElMessage.error("收藏失败: " + error.message);
  });
}

function removeCollect() {
  if (!info.value.collect) {
    ElMessage.warning("您还未收藏此商品");
    return;
  }
  
  let ids = [info.value.collect];
  
  request.delete("/api/productCollect/delBatch", {data: ids}).then(res => {
    if (res.code === 1) {
      info.value.collect = null;
      ElMessage({
        message: "取消收藏成功",
        type: 'success'
      });
    } else {
      ElMessage.error(res.msg || "取消收藏失败");
    }
  }).catch(error => {
    ElMessage.error("取消收藏失败: " + error.message);
  });
}

function addShoppingCart() {

  request.post("/api/shoppingCart/add", {

    productId: id.value, 
    quantity: quantity.value
  }).then(res => {
    if (res.code === 1) {
      ElMessage({
        message: "添加成功",
        type: 'success'
      });
    } else {
      ElMessage.error("添加失败");
    }
  }).catch(error => {
    ElMessage.error("添加失败: " + error.message);
  });
}

const buyDialogOpen = ref(false)
const productOrder = ref({})
const buyFormRef = ref()

function buy() {
  productOrder.value = {}
  productOrder.value.quantity = 1
  buyDialogOpen.value = true
}

function buySubmit() {
  buyFormRef.value.validate((valid) => {
    if (!valid) {
      ElMessage({
        message: "验证失败，请检查表单!",
        type: 'warning'
      });
      return;
    }
    
    let shippingAddress = shippingAddressList.value.find(item => item.id == productOrder.value.shippingAddressId);
    if (!shippingAddress) {
      ElMessage.error("请选择收货地址");
      return;
    }
    
    // 设置订单信息
    productOrder.value.productId = id.value;
    productOrder.value.address = shippingAddress.address;
    productOrder.value.name = shippingAddress.name;
    productOrder.value.tel = shippingAddress.tel;
    productOrder.value.userMessage = productOrder.value.remark || '';
    
    // 创建商品列表
    const productList = [{
      pid: id.value,
      number: productOrder.value.quantity,
    }];
    
    productOrder.value.productList = productList;
    
    request.post("/api/productOrder/add", productOrder.value).then(res => {
      if (res.code === 1) {
        buyDialogOpen.value = false;
        ElMessage({
          message: "订单创建成功",
          type: 'success'
        });
        router.push("/productOrder");
      } else {
        ElMessage.error(res.msg || "订单创建失败");
      }
    }).catch(error => {
      ElMessage.error("订单创建失败: " + error.message);
    });
  });
}

function setCurrentImage(index) {
  currentImage.value = index;
  if (carousel.value) {
    carousel.value.setActiveItem(index);
  }
}

</script>

<style scoped>
.product-details {
  background-color: white;
  min-height: 100vh;
  padding: 20px 0;
}

.product-container {
  max-width: 1200px;
  margin: 0 auto;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.product-main {
  padding: 20px;
}

.product-gallery {
  position: relative;
}

.gallery-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.thumbnail-list {
  display: flex;
  gap: 10px;
  margin-top: 10px;
  overflow-x: auto;
  padding: 5px 0;
}

.thumbnail-item {
  width: 60px;
  height: 60px;
  border: 1px solid #eee;
  cursor: pointer;
  overflow: hidden;
}

.thumbnail-item:hover {
  border-color: #ff5000;
}

.thumbnail-item.active {
  border-color: #ff5000;
  border-width: 2px;
  box-shadow: 0 0 5px rgba(255, 80, 0, 0.5);
}

.product-info {
  padding: 0 20px;
}

.product-title {
  font-size: 20px;
  color: #333;
  margin-bottom: 20px;
  line-height: 1.4;
}

.price-section {
  background-color: #fff5f5;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.price-label {
  color: #999;
  font-size: 14px;
}

.price-value {
  color: #ff5000;
  font-size: 28px;
  font-weight: bold;
  margin: 5px 0;
}

.original-price {
  color: #999;
  text-decoration: line-through;
  font-size: 14px;
}

.promotion-section {
  margin-bottom: 20px;
}

.promotion-item {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
}

.service-section {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
  padding: 10px 0;
  border-top: 1px solid #eee;
  border-bottom: 1px solid #eee;
}

.service-item {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #666;
}

.selection-section {
  margin-bottom: 20px;
}

.selection-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.label {
  color: #666;
  width: 60px;
}

.stock {
  color: #999;
  margin-left: 10px;
}

.action-section {
  display: flex;
  gap: 0px;
  margin-top: 30px;
  align-items: center;
}

.action-section .el-button {
  flex: 1;
  height: 48px;
  font-size: 16px;
  font-weight: bold;
}

.blf {
  border-radius: 15px 0 0 15px;
  margin: 0px;
  width: 180px;
}

.brt {
  border-radius: 0 15px 15px 0;
  margin: 0px;
  width: 180px;
}

.collect-btn {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 80px;
  height: 48px;
  margin-left: 15px;
  cursor: pointer;
  border: none;
  transition: all 0.3s;
}

.collect-btn:hover {
  color: #ff5000;
}

.collect-btn .el-icon {
  font-size: 20px;
  margin-bottom: 2px;
}

.collect-btn span {
  font-size: 12px;
  color: #666;
}

.collect-btn:hover span {
  color: #ff5000;
}

.collect-btn .collected {
  color: #ff5000;
}

.collect-btn .collected + span {
  color: #ff5000;
}

.product-detail-section {
  margin-top: 20px;
  padding: 20px;
}

.detail-tabs {
  margin-top: 20px;
}

.detail-content {
  padding: 20px 0;
}

.detail-content img {
  max-width: 100%;
  height: auto;
}

.specs-content {
  text-overflow: ellipsis;
  padding: 20px 0;
}

:deep(.el-tabs__item) {
  font-size: 16px;
  height: 50px;
  line-height: 50px;
}

:deep(.el-tabs__item.is-active) {
  color: #ff5000;
}

:deep(.el-tabs__active-bar) {
  background-color: #ff5000;
}
</style>
